class Solution
{
public:
    int minOperations(vector<int> &nums)
    {
        int n = nums.size();
        int allGcd = gcd(nums[0], nums[1]);
        for (int i = 2; i < n; ++i)
        {
            allGcd = gcd(allGcd, nums[i]);
            if (allGcd == 1)
            {
                break;
            }
        }
        if (allGcd != 1)
        {
            return -1;
        }

        int oneCount = 0;
        for (int i = 0; i < n; ++i)
        {
            if (nums[i] == 1)
            {
                ++oneCount;
            }
        }
        if (oneCount != 0)
        {
            return n - oneCount;
        }

        int minLen = n;
        for (int i = 0; i < n - 1; ++i)
        {
            int partGcd = nums[i];
            for (int j = i + 1; j < n; ++j)
            {
                partGcd = gcd(partGcd, nums[j]);
                if (partGcd == 1)
                {
                    minLen = min(minLen, j - i + 1);
                    break;
                }
            }
        }
        return minLen + n - 2;
    }
};